// 三维模型相关的组合式函数
import { ref } from 'vue'
import * as Cesium from 'cesium'

export function useCesium() {
  // 响应式数据
  const cesiumContainer = ref()
  const isLoading = ref(false)
  const loadingText = ref('正在初始化3D视图...')
  const errorMessage = ref('')
  const successMessage = ref('')

  // Cesium实例
  let viewer = null
  let currentTileset = null

 // 模型的实际地理坐标 - 使用已知的模型位置
  const MODEL_COORDINATES = ref({
    longitude: 113.87559234768288,  // 从之前的日志中获取的实际坐标
    latitude: 27.629125349519814,
    height: 0
  })

  // 初始化Cesium
  const initCesium = async () => {
    if (!cesiumContainer.value) {
      console.error('Cesium container not found')
      return false
    }

    try {
      isLoading.value = true
      loadingText.value = '正在初始化3D视图...'

      // 设置Cesium资源路径
      if (import.meta.env.DEV) {
        window.CESIUM_BASE_URL = '/node_modules/cesium/Build/Cesium/'
      } else {
        window.CESIUM_BASE_URL = '/cesium/'
      }

      const container = cesiumContainer.value

      // 创建Cesium Viewer - 使用最简单的配置，完全参考 kiro-twins
      viewer = new Cesium.Viewer(container, {
        baseLayerPicker: false,
        geocoder: false,
        homeButton: false,
        sceneModePicker: false,
        navigationHelpButton: false,
        animation: false,
        timeline: false,
        fullscreenButton: true,
        vrButton: false,
        infoBox: false,  // 禁用信息框避免沙箱问题
        selectionIndicator: true  // 启用选择指示器
      })

      // 确保地球可见
      viewer.scene.globe.show = true
      viewer.scene.skyBox.show = true
      viewer.scene.skyAtmosphere.show = true


      // 设置初始视角到默认位置（北京坐标）
      const defaultLng = 116.3974
      const defaultLat = 39.9093
      const defaultHeight = 1000

      viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(defaultLng, defaultLat, defaultHeight),
        orientation: {
          heading: 0,
          pitch: Cesium.Math.toRadians(-45),
          roll: 0
        }
      })

      // 如果模型坐标还未设置，使用默认坐标
      if (!MODEL_COORDINATES.value.longitude) {
        MODEL_COORDINATES.value.longitude = defaultLng
        MODEL_COORDINATES.value.latitude = defaultLat
        MODEL_COORDINATES.value.height = 0
      }

      console.log('Cesium initialized successfully')
      console.log('Imagery layers:', viewer.imageryLayers.length)

      // 自动加载卫星图像（不阻塞初始化）
      setTimeout(() => {
        switchToSatellite().catch(error => {
          console.warn('自动加载卫星图像失败，使用默认地图:', error)
        })
      }, 500)

      // 延迟加载3D城市模型（不阻塞初始化）
      setTimeout(() => {
        loadCityModel().catch(error => {
          console.warn('3D城市模型加载失败，但不影响基础功能:', error)
        })
      }, 1000)

      return true

    } catch (error) {
      console.error('Failed to initialize Cesium:', error)
      showError('初始化3D视图失败: ' + error.message)
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 加载3D城市模型
  const loadCityModel = async () => {
    if (!viewer) {
      showError('Viewer未初始化')
      return
    }

    try {
      isLoading.value = true
      loadingText.value = '正在加载3D城市模型...'

      // 移除现有模型
      if (currentTileset) {
        viewer.scene.primitives.remove(currentTileset)
        currentTileset = null
      }

      // 加载3D城市模型（带超时）
      const tilesetPromise = Cesium.Cesium3DTileset.fromUrl('/Data/tileset.json', {
        // 优化加载参数
        skipLevelOfDetail: false,
        baseScreenSpaceError: 1024,
        skipScreenSpaceErrorFactor: 16,
        skipLevels: 1,
        immediatelyLoadDesiredLevelOfDetail: false,
        loadSiblings: false,
        cullWithChildrenBounds: true,
        // 确保模型正确定位
        maximumScreenSpaceError: 16
      })

      // 设置10秒超时
      const timeoutPromise = new Promise((_, reject) => {
        setTimeout(() => reject(new Error('3D模型加载超时')), 10000)
      })

      const tileset = await Promise.race([tilesetPromise, timeoutPromise])
      viewer.scene.primitives.add(tileset)

      // 等待tileset准备就绪（也设置超时）
      const readyTimeoutPromise = new Promise((_, reject) => {
        setTimeout(() => reject(new Error('3D模型准备超时')), 5000)
      })

      await Promise.race([tileset.readyPromise, readyTimeoutPromise])

      const heightOffset = -250;
      const translation = Cesium.Cartesian3.fromElements(0.0, 0.0, heightOffset);
      tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);

      // 尝试从变换矩阵中提取实际的地理位置
      let longitude, latitude, height

      try {
        const transform = tileset.root.transform
        const position = Cesium.Matrix4.getTranslation(transform, new Cesium.Cartesian3())

        // 检查position是否有效
        if (position && !isNaN(position.x) && !isNaN(position.y) && !isNaN(position.z)) {
          const cartographic = Cesium.Cartographic.fromCartesian(position)

          if (cartographic) {
            longitude = Cesium.Math.toDegrees(cartographic.longitude)
            latitude = Cesium.Math.toDegrees(cartographic.latitude)
            height = cartographic.height

            console.log('Model position extracted from transform:', { longitude, latitude, height })
          } else {
            throw new Error('无法从笛卡尔坐标转换为地理坐标')
          }
        } else {
          throw new Error('变换矩阵中的位置无效')
        }
      } catch (transformError) {
        console.warn('从变换矩阵提取位置失败:', transformError)

        // 尝试使用tileset的boundingSphere作为备选方案
        try {
          const boundingSphere = tileset.boundingSphere
          if (boundingSphere && boundingSphere.center) {
            const cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center)
            if (cartographic) {
              longitude = Cesium.Math.toDegrees(cartographic.longitude)
              latitude = Cesium.Math.toDegrees(cartographic.latitude)
              height = cartographic.height
              console.log('Model position extracted from bounding sphere:', { longitude, latitude, height })
            } else {
              throw new Error('无法从边界球转换为地理坐标')
            }
          } else {
            throw new Error('边界球无效')
          }
        } catch (boundingError) {
          console.warn('从边界球提取位置也失败:', boundingError)

          // 使用默认坐标作为最后的备选方案
          longitude = MODEL_COORDINATES.value.longitude || 116.3974
          latitude = MODEL_COORDINATES.value.latitude || 39.9093
          height = MODEL_COORDINATES.value.height || 0

          console.log('使用默认坐标:', { longitude, latitude, height })
        }
      }

      // 更新模型坐标
      MODEL_COORDINATES.value.longitude = longitude
      MODEL_COORDINATES.value.latitude = latitude
      MODEL_COORDINATES.value.height = height

      console.log('模型坐标已更新:', MODEL_COORDINATES.value)

      // 自动飞到模型位置，提供更好的初始视角
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(longitude, latitude, height + 800),
        orientation: {
          heading: 0,
          pitch: Cesium.Math.toRadians(-30), // 稍微调整俯仰角度
          roll: 0
        },
        duration: 2.0 // 缩短飞行时间
      })

      currentTileset = tileset
      showSuccess('3D城市模型加载成功，已自动定位到模型位置')

    } catch (err) {
      console.error('加载3D城市模型失败:', err)
      showError('3D城市模型加载失败: ' + err.message)
    } finally {
      isLoading.value = false
    }
  }

  // 切换到卫星图像
  const switchToSatellite = async () => {
    if (!viewer) {
      showError('Viewer未初始化')
      return
    }

    try {
      console.log('Switching to satellite imagery...')

      // 尝试多个卫星图像提供者，按优先级排序
      const providers = [
        {
          name: 'Cesium World Imagery',
          create: async () => {
            try {
              return await Cesium.createWorldImageryAsync()
            } catch (error) {
              console.warn('Cesium World Imagery failed, trying fallback')
              throw error
            }
          }
        },
        {
          name: 'ESRI World Imagery',
          create: async () => {
            try {
              return await Cesium.ArcGisMapServerImageryProvider.fromUrl(
                'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'
              )
            } catch (error) {
              console.warn('ESRI World Imagery failed, trying alternative')
              // 备用ESRI服务
              return await Cesium.ArcGisMapServerImageryProvider.fromUrl(
                'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'
              )
            }
          }
        },
        {
          name: 'OpenStreetMap',
          create: () => new Cesium.OpenStreetMapImageryProvider({
            url: 'https://a.tile.openstreetmap.org/'
          })
        },
        {
          name: 'CartoDB Positron',
          create: () => new Cesium.UrlTemplateImageryProvider({
            url: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
            subdomains: ['a', 'b', 'c', 'd']
          })
        }
      ]

      let success = false
      for (const provider of providers) {
        try {
          console.log(`Trying ${provider.name}...`)

          // 为每个提供者设置超时
          const timeoutPromise = new Promise((_, reject) => {
            setTimeout(() => reject(new Error(`${provider.name} timeout`)), 5000)
          })

          const imageryProvider = await Promise.race([provider.create(), timeoutPromise])

          // 验证 imageryProvider 是否有效
          if (!imageryProvider) {
            throw new Error('Imagery provider is null or undefined')
          }

          // 移除现有的图像层（除了第一个基础层）
          while (viewer.imageryLayers.length > 1) {
            viewer.imageryLayers.remove(viewer.imageryLayers.get(viewer.imageryLayers.length - 1))
          }

          // 添加新的图像层
          const layer = viewer.imageryLayers.addImageryProvider(imageryProvider)
          layer.alpha = 1.0
          layer.show = true

          // 等待一小段时间确保图层加载
          await new Promise(resolve => setTimeout(resolve, 100))

          console.log(`Successfully added ${provider.name}`)
          showSuccess(`已自动加载${provider.name}卫星图像`)
          success = true
          break

        } catch (error) {
          console.warn(`${provider.name} failed:`, error)
          // 继续尝试下一个提供者
        }
      }

      if (!success) {
        console.warn('所有卫星图像提供者都无法加载，保持当前地图')
        showError('卫星图像暂时无法加载，请稍后重试')

        // 确保至少有基础地图可用
        if (viewer.imageryLayers.length === 0) {
          // 如果没有任何图层，添加一个基础的 OpenStreetMap
          try {
            const fallbackProvider = new Cesium.OpenStreetMapImageryProvider({
              url: 'https://a.tile.openstreetmap.org/'
            })
            viewer.imageryLayers.addImageryProvider(fallbackProvider)
            console.log('Added fallback OpenStreetMap')
          } catch (fallbackError) {
            console.error('Even fallback provider failed:', fallbackError)
          }
        }
      }

    } catch (error) {
      console.error('Switch to satellite failed:', error)
      showError('切换卫星图像失败: ' + error.message)
    }
  }

  // 切换到基础地图
  const switchToBaseMap = async () => {
    if (!viewer) {
      showError('Viewer未初始化')
      return
    }

    try {
      console.log('Switching to base map...')

      // 移除所有额外的图像层，只保留默认的基础层
      while (viewer.imageryLayers.length > 1) {
        viewer.imageryLayers.remove(viewer.imageryLayers.get(viewer.imageryLayers.length - 1))
      }

      // 确保基础层可见
      const baseLayer = viewer.imageryLayers.get(0)
      if (baseLayer) {
        baseLayer.show = true
        baseLayer.alpha = 1.0
      }

      showSuccess('已切换到基础地图')

    } catch (error) {
      console.error('Switch to base map failed:', error)
      showError('切换基础地图失败: ' + error.message)
    }
  }

  // 重置相机视角
  const resetCamera = () => {
    if (!viewer) return

    if (currentTileset) {
      viewer.zoomTo(currentTileset, new Cesium.HeadingPitchRange(0, Cesium.Math.toRadians(-45), 500))
    } else if (MODEL_COORDINATES.value.longitude && MODEL_COORDINATES.value.latitude) {
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          MODEL_COORDINATES.value.longitude,
          MODEL_COORDINATES.value.latitude,
          MODEL_COORDINATES.value.height + 1000
        ),
        orientation: {
          heading: 0,
          pitch: Cesium.Math.toRadians(-45),
          roll: 0
        },
        duration: 2.0
      })
    } else {
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(116.3974, 39.9093, 1000),
        orientation: {
          heading: 0,
          pitch: Cesium.Math.toRadians(-45),
          roll: 0
        },
        duration: 2.0
      })
    }
  }

  // 工具函数
  const showError = (message) => {
    errorMessage.value = message
    setTimeout(() => {
      errorMessage.value = ''
    }, 5000)
  }

  const showSuccess = (message) => {
    console.log('Success:', message)
    successMessage.value = message
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)
  }

  const clearError = () => {
    errorMessage.value = ''
  }

  const clearSuccess = () => {
    successMessage.value = ''
  }

  // 清理函数
  const cleanup = () => {
    if (viewer) {
      viewer.destroy()
      viewer = null
    }
  }

  return {
    // 响应式数据
    cesiumContainer,
    isLoading,
    loadingText,
    errorMessage,
    successMessage,
    MODEL_COORDINATES,

    // 方法
    initCesium,
    loadCityModel,
    switchToSatellite,
    switchToBaseMap,
    resetCamera,
    showError,
    showSuccess,
    clearError,
    clearSuccess,
    cleanup,

    // Cesium实例访问器
    getViewer: () => viewer,
    getCurrentTileset: () => currentTileset
  }
}